/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.starter.integration.module.context;

import org.aopalliance.aop.Advice;
import org.apache.commons.lang3.StringUtils;
import org.pajamas.daydream.serializer.json.Jsons;
import org.pajamas.daydream.template.sequence.SequenceTemplate;
import org.pajamas.daydream.template.sequence.context.PropertyContext;
import org.pajamas.daydream.template.sequence.context.SpELContext;
import org.pajamas.daydream.template.sequence.segment.SegmentDefinitionParser;
import org.pajamas.daydream.template.sequence.segment.SegmentTokenSplitter;
import org.pajamas.starter.integration.daydream.sequenceTemplate.JsonValueSerializerTokenSplitterRule;
import org.pajamas.starter.integration.daydream.sequenceTemplate.SequenceBindingAdvice;
import org.pajamas.starter.integration.spring.aop.AspectJAdvisorBuilder;
import org.pajamas.starter.integration.spring.bean.BeanConstants;
import org.pajamas.starter.integration.spring.expression.EvaluationContextBuilder;
import org.springframework.aop.Advisor;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.expression.spel.support.StandardEvaluationContext;

/**
 * @author william
 * @since 2024/4/15
 */
@ConditionalOnProperty(prefix = "org.pajamas.starter.context.sequence", name = "enabled", havingValue = "true",
        matchIfMissing = true)
@EnableConfigurationProperties(PajamasSequenceProperties.class)
public class PajamasSequenceAutoConfiguration {
    private static final String SEQUENCE_PATTERN_ASPECTJ_EXPRESSION =
            "execution (* {" + PajamasPropSrcConstants.BASE_PACKAGE_APP + "}..service.*Service.*(..)) " +
                    "&& @within(org.springframework.stereotype.Service)" +
                    "&& args(org.pajamas.daydream.template.sequence.annotation.SequenceBinding, ..)";

    @Order(BeanConstants.ORDER_LATEST_SECOND)
    @Bean
    public EvaluationContextBuilder.Customizer defaultEvaluationContextBuilderCustomizer(
            ApplicationContext applicationContext) {
        return builder -> {
            builder.beanResolver(new BeanFactoryResolver(applicationContext));
        };
    }

    @ConditionalOnProperty(prefix = "org.pajamas.starter.context.sequence", name = "sequenceTemplate",
            havingValue = "true", matchIfMissing = true)
    @ConditionalOnMissingBean
    @Bean
    public SequenceTemplate pajamasSequenceTemplate(Environment environment,
                                                    ObjectProvider<EvaluationContextBuilder.Customizer> customizers) {
        SegmentDefinitionParser segmentDefinitionParser = new SegmentTokenSplitter(null, null,
                new JsonValueSerializerTokenSplitterRule(Jsons.NO_OP));
        StandardEvaluationContext evaluationContext = EvaluationContextBuilder
                .newBuilder()
                .customizers(customizers.orderedStream().iterator())
                .build();
        return new SequenceTemplate(segmentDefinitionParser,
                new PropertyContext(environment),
                new SpELContext(evaluationContext));
    }

    @ConditionalOnProperty(prefix = "org.pajamas.starter.context.sequence", name = "sequenceBindingAdvice",
            havingValue = "true", matchIfMissing = true)
    @Order(BeanConstants.ORDER_EARLIEST)
    @Bean("pajamasSequenceBindingAdvice")
    public Advice pajamasSequenceBindingAdvice() {
        return new SequenceBindingAdvice();
    }

    @ConditionalOnBean(value = Advice.class, name = "pajamasSequenceBindingAdvice")
    @Bean
    public Advisor pajamasSequenceBindingAdvisor(@Qualifier("pajamasSequenceBindingAdvice") Advice advice,
                                                 PajamasSequenceProperties properties,
                                                 SequenceTemplate sequenceTemplate) {
        String defaultsAspectJExpression = sequenceTemplate.create(SEQUENCE_PATTERN_ASPECTJ_EXPRESSION).interpretSelf();
        return AspectJAdvisorBuilder
                .newBuilder()
                .pointcut(StringUtils.firstNonBlank(properties.getAspectjExpression(), defaultsAspectJExpression))
                .advice(advice)
                .build();
    }
}
